package com.inga.utils.httpclient;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * deal HttpResponse to do something , like : package HashMap or response html
 *
 * Created by abing on 2015/11/25.
 */
public class HttpDataCommon {

    /**
     * deal HttpResponse header Set-Cookie to package Map
     *
     * @param response
     * @return
     */
    public static Map<String , String> getCookieMap(HttpResponse response){

        Map<String , String> cookieData = new HashMap<String,String>();

        if (response != null){
            Header[] headers = response.getAllHeaders();
            String cookie , cookieName , cookieValue;
            for (Header header : headers){
                if (header.equals("Set-Cookie")){
                    cookie = header.getValue();
                    cookieName = cookie.split("=")[0];
                    cookieValue = cookie.split("=")[1].split(";")[0];

                    cookieData.put(cookieName , cookieValue);
                }
            }
        }
        return  cookieData;
    }

    /**
     * deal Html HttpResponse to String to show
     *
     * @param response  //the html requet to back Response
     * @return html     //the response html String
     */
    public static String responseToString(HttpResponse response){

        StringBuilder sb = new StringBuilder();
        HttpEntity entity = response.getEntity();

        try {
            sb.append(EntityUtils.toString(entity).trim());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
